package com.eolwral.osmonitor;

import com.eolwral.osmonitor.preferences.Preferences;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class BootUpReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {

		// load settings
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		
        if(settings.getBoolean(Preferences.PREF_AUTOSTART, false) && 
        		settings.getBoolean(Preferences.PREF_STATUSBAR, false))
        {
        	context.startService(new Intent(context, OSMonitorService.class));
        }
        
        if(settings.getBoolean(Preferences.PREF_AUTOSETCPU, false))
        {
        	String CPUGov = settings.getString(Preferences.PREF_SETCPUGOV, "");
        	StringBuilder SetCPUCmd = new StringBuilder();
        	
        	if(!CPUGov.equals(""))
        	{
        		// We need to delay this for about 3 minutes; otherwise this may cause
        		// some kernels to hit a deadlock.
        		try
        		{
					Thread.sleep(180000);
				}
        		catch (InterruptedException e)
        		{
        			//This should not execute.
				}
        		
        		for(int CPUNum = 0; CPUNum < CpuStat.GetCpuCount(); CPUNum++)
        		{
        			SetCPUCmd.append("echo ");
        			SetCPUCmd.append(CPUGov);
        			SetCPUCmd.append(" > /sys/devices/system/cpu/cpu");
        			SetCPUCmd.append(CPUNum);
        			SetCPUCmd.append("/cpufreq/scaling_governor");
        			SetCPUCmd.append('\n');
        		}
        	}
        	
        	String CPUFreq[] = settings.getString(Preferences.PREF_SETCPURANGE, ";").split(";");
        	if(CPUFreq.length == 2)
        	{
        		for(int CPUNum = 0; CPUNum < CpuStat.GetCpuCount(); CPUNum++)
        		{
        			SetCPUCmd.append("echo ");
        			SetCPUCmd.append(CPUFreq[0]);
        			SetCPUCmd.append(" > /sys/devices/system/cpu/cpu");
        			SetCPUCmd.append(CPUNum);
        			SetCPUCmd.append("/cpufreq/scaling_min_freq");
        			SetCPUCmd.append('\n');

        			SetCPUCmd.append("echo ");
        			SetCPUCmd.append(CPUFreq[1]);
        			SetCPUCmd.append(" > /sys/devices/system/cpu/cpu");
        			SetCPUCmd.append(CPUNum);
        			SetCPUCmd.append("/cpufreq/scaling_max_freq");
        			SetCPUCmd.append('\n');
        		}		
        	}
    		CommonUtil.execCommand(SetCPUCmd.toString());
        }
	}
}
